package io.aircraft.modules.job.task;

import io.aircraft.common.constant.Constant;
import io.aircraft.common.utils.ApiResult;
import io.aircraft.modules.job.dto.VwPostWcsDTO;
import io.aircraft.modules.job.entity.ProcAckByWcsHandleEntity;
import io.aircraft.modules.job.service.ProcAckByWcsHandleService;
import io.aircraft.modules.job.service.VwPostWcsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component("postWcsTask")
public class PostWcsTask implements ITask {
    private final VwPostWcsService postWcsService;
    private final ProcAckByWcsHandleService ackByWcsHandleService;
    private final RestTemplate restTemplate;
    private final Logger logger = LoggerFactory.getLogger(getClass());

    public PostWcsTask(VwPostWcsService postWcsService, ProcAckByWcsHandleService ackByWcsHandleService, RestTemplate restTemplate) {
        this.postWcsService = postWcsService;
        this.ackByWcsHandleService = ackByWcsHandleService;
        this.restTemplate = restTemplate;
    }

    @Override
    public void run(String params) {
        //1.扫描[vw_post_wcs]信息,有就下发给wcs系统
        VwPostWcsDTO postInfo = postWcsService.getOne();
        if (postInfo == null) {
            return;
        }
        //2.调用wcs系统提供的api
        try {
            //2.1.更新post信息状态
            ApiResult respond = restTemplate.postForObject(params, postInfo, ApiResult.class);
            if (respond == null) {
                return;
            }
            //3.搜集反馈参数
            ProcAckByWcsHandleEntity parameters = new ProcAckByWcsHandleEntity();
            parameters.setRequestPk(respond.getRequestPk());
            parameters.setCode(respond.getCode());
            parameters.setMsg(respond.getMsg());
            parameters.setUserId(Constant.ClientCode.WCS.getId());
            //4.调用存储过程处理接收到的反馈结果
            ackByWcsHandleService.ackHandle(parameters);
        } catch (Exception ex) {
            logger.error("设备任务下发wcs系统异常!!!异常类型:" + ex.getMessage());
        }
    }
}
